<?php
namespace app\api\controller;

use think\Controller;
use app\common\wx\User;
use app\common\wx\Custom;
use app\common\wx\Token;
use think\cache\driver\Redis;

/**
 * 微信回调接口
 */
class Callback extends Controller
{
    public function index()
    {
        if (!isset($_GET['echostr'])) {
           $this->respond();
        } else {
            $this->valid();
        }
    }

    //验证签名
    public function valid()
    {
         $echoStr = $_GET["echostr"];
         $signature = $_GET["signature"];
         $timestamp = $_GET["timestamp"];
         $nonce = $_GET["nonce"];
         //$token = TOKEN;
         $token = 'yixiaowai';
         $tmpArr = array($token, $timestamp, $nonce);
         sort($tmpArr);
         $tmpStr = implode($tmpArr);
         $tmpStr = sha1($tmpStr);
         if($tmpStr == $signature){
             echo $echoStr;
             exit;
         }
    }

    /**
    * 微信回调接口入口方法
    * @var object
    * @return string
    */
    public function respond()
    {
        $postStr = file_get_contents("php://input");        
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr);
            $RX_TYPE = trim($postObj->MsgType);
            switch($RX_TYPE){
                case "event"://事件
                    $this->receiveEvent($postObj);
                    break;
                case "text"://文本回复
                    $this->receiveText($postObj);
                    break;
                case "image"://图片
				    $this->receiveImage($postObj);
					break;
				case "miniprogrampage"://小程序卡片消息
					$this->receiveLocation($postObj);
					break;                
            }
        }
    }

    /**
    * 事件接收
    * @var object
    * @return string
    */
    private function receiveEvent($object){
        switch($object->Event){
            case "user_enter_tempsession"://进入会话事件(自动回复)
                $openid = addslashes($object->FromUserName);
                $sessionfrom = addslashes($object->SessionFrom);
                $original_id = addslashes($object->ToUserName);
                $nt = date("H:i:s",time());
                $mt = date("00:00:00",time());
                $maxt = date("23:59:59",time());

                $wx_reply_info = model("AutoReplyModel")->where("session_from",$sessionfrom)->find();                
                $starttime = date("H:i:s",$wx_reply_info['start_time']);
                $endtime = date("H:i:s",$wx_reply_info['end_time']);

                if($wx_reply_info['isopen'] && (($starttime< $endtime && $starttime<=$nt && $endtime>$nt)||$starttime == $endtime)||$starttime>$endtime &&($nt>=$starttime && $nt<=$maxt || $nt>=$mt && $nt<=$endtime)){
                    $reply_data = json_decode($wx_reply_info['reply_data'],true);                    
                    if($reply_data['type']==1){
                        //文本回复
                        if(!empty($reply_data['replydata'])){
                            $custom = new Custom();
                            $data = array(
                                'touser' => $openid,
                                'msgtype' => 'text',
                                'text' => array('content' =>$reply_data['replydata'])
                            );
                            $custom->send($original_id,$data);
                        }
                    }else if($reply_data['type']==2){
                        //图文回复
                        $list = model("ImageTextInGroupModel")->field("b.*")->alias('a')->join('ImageText b','a.image_text_id=b.id','LEFT')->where("group_id",$reply_data['replydata'])->select();
                        
                        if($list){
                            $imagetextinfo = $list[array_rand($list)];
                            $thumb_url = $imagetextinfo['pic'];
                            if(!preg_match("/^(http:\/\/|https:\/\/).*$/",$thumb_url)){
                                $thumb_url = config("aliyun_oss.MainPath").'/'.$thumb_url;
                            }                            
                            
                            $custom = new Custom();
                            $data = array(
                                'touser' => $openid,
                                'msgtype' => 'link',
                                'link' => array(
                                    "title" => $imagetextinfo['title'],
                                    "thumb_url" => $thumb_url,
                                    "url" => $imagetextinfo['url'],
                                    "description" => $imagetextinfo['desc'])
                            );                        
                            $custom->send($original_id,$data);
                        }
                    }else{
                        //图片回复
                        $list = model("ImageInGroupModel")->field("b.*")->alias('a')->join('Image b','a.image_id=b.id','LEFT')->where("group_id",$reply_data['replydata'])->select();
                        if($list){
                            $imageinfo = $list[array_rand($list)];
                            $image_id = $imageinfo['id'];
                            //图片上传临时服务器
                            $redis_key = "jk_reply_image_{$original_id}_{$image_id}";
                            $redis = new Redis();
                            
                            if($redis->get($redis_key)){
                                $media_id = $redis->get($redis_key);
                            }else{
                                $token =  new Token();
                                $access_token = $token->getAccessToken($original_id);
                                //上传图片到临时库
                                $pic_path = ROOT_PATH.'public_html/'.$imageinfo['image_url'];
                                $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type=image';
                                $info = $this->curl_post_file($pic_path,$url);
                                $arr = json_decode($info,true);
                                $media_id = $arr['media_id'];
                                $redis->set($redis_key,$media_id,3600*6);
                            }
                            
                            $custom = new Custom();
                            $data = array(
                                'touser' => $openid,
                                'msgtype' => 'image',
                                'image' => array(
                                    "media_id" => $media_id
                                )
                            );
                            $custom->send($original_id,$data);
                        }
                    }
                }
                break;           
        }
    }

    /**
    * 文本消息接收
    * @var object
    * @return string
    */
    private function receiveText($object){
        //文本回复
        $keywords = addslashes(trim($object->Content));        
        if($keywords){
            $openid = addslashes($object->FromUserName);
            $original_id = addslashes($object->ToUserName);

            if($keywords == "getmyopenid"){
                $data['original_id'] = $original_id;
                $data['openid'] = $openid;
                $data['addtime'] = time();
                $data['uptime'] = $data['addtime'];
                $wxuserinfo = model("SysWechatUserModel")->where(["openid"=>$openid,"original_id"=>$original_id])->find();
                if($wxuserinfo){
                    unset($data['addtime']);
                    model("SysWechatUserModel")->allowField(true)->save($data,["id"=>$wxuserinfo["id"]]);
                }else{
                    model("SysWechatUserModel")->allowField(true)->save($data);
                }
            }else{
                $keywordreply = model("KeyWordsReplyModel")->where(["keywords"=>$keywords,"isopen"=>1])->find();
                if($keywordreply){
                    $reply_data = json_decode($keywordreply['reply_data'],true);
                    if($reply_data['type']==1){
                        //文本回复
                        if(!empty($reply_data['replydata'])){
                            $custom = new Custom();
                            $data = array(
                                'touser' => $openid,
                                'msgtype' => 'text',
                                'text' => array('content' =>$reply_data['replydata'])
                            );
                            $custom->send($original_id,$data);
                        }
                    }else if($reply_data['type']==2){
                        //图文回复
                        $list = model("ImageTextInGroupModel")->field("b.*")->alias('a')->join('ImageText b','a.image_text_id=b.id','LEFT')->where("group_id",$reply_data['replydata'])->select();
                        
                        if($list){
                            $imagetextinfo = $list[array_rand($list)];
                            $thumb_url = $imagetextinfo['pic'];
                            if(!preg_match("/^(http:\/\/|https:\/\/).*$/",$thumb_url)){
                                $thumb_url = config("aliyun_oss.MainPath").'/'.$thumb_url;
                            }                            
                            
                            $custom = new Custom();
                            $data = array(
                                'touser' => $openid,
                                'msgtype' => 'link',
                                'link' => array(
                                    "title" => $imagetextinfo['title'],
                                    "thumb_url" => $thumb_url,
                                    "url" => $imagetextinfo['url'],
                                    "description" => $imagetextinfo['desc'])
                            );                        
                            $custom->send($original_id,$data);
                        }
                    }else{
                        //图片回复
                        $list = model("ImageInGroupModel")->field("b.*")->alias('a')->join('Images b','a.image_id=b.id','LEFT')->where("group_id",$reply_data['replydata'])->select();
                        if($list){
                            $imageinfo = $list[array_rand($list)];
                            $image_id = $imageinfo['id'];
                            //图片上传临时服务器
                            $redis_key = "jk_reply_image_{$original_id}_{$image_id}";
                            $redis = new Redis();
                            
                            if($redis->get($redis_key)){
                                $media_id = $redis->get($redis_key);
                            }else{
                                $token =  new Token();
                                $access_token = $token->getAccessToken($original_id);
                                //上传图片到临时库
                                $pic_path = ROOT_PATH.'public_html/'.$imageinfo['image_url'];
                                $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type=image';
                                $info = $this->curl_post_file($pic_path,$url);
                                $arr = json_decode($info,true);
                                $media_id = $arr['media_id'];
                                $redis->set($redis_key,$media_id,3600*6);
                            }
                            
                            $custom = new Custom();
                            $data = array(
                                'touser' => $openid,
                                'msgtype' => 'image',
                                'image' => array(
                                    "media_id" => $media_id
                                )
                            );
                            $custom->send($original_id,$data);
                        }
                    }
                }
            }
        }
    }

    /**
    * 图片消息接收
    * @var object
    * @return string
    */
    private function receiveImage($object){
        return "";
    }

    /**
    * 小程序卡片消息接收
    * @var object
    * @return string
    */
    private function receiveLocation($object){
        return "";
    }

    //上传图片素材
    public function curl_post_file($file, $url)
    {
        if (class_exists('\CURLFile')) {
            $data = array('media' => new \CURLFile(realpath($file)));
        }else {
            $data = array('media' => '@' . realpath($file));
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        }else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        @curl_setopt($ch, CURLOPT_INFILESIZE,filesize($file));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}